import express from 'express'
import cookieParser from 'cookie-parser'

import { config } from './config/index.js'
import { userRouter, linksRouter, commentRouter, discussRouter, adminRouter } from './router/index.js'
import { findUserById } from './model/user.js'

const NONEEDLOGIN = ["/api/user/login", "/api/user/register"] //无需登陆的页面
const app = express()
//配置支持解析body

app.use("/avator", express.static('./public/avator'))
app.use("/icon", express.static('./public/icon'))

app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cookieParser())

app.use((req, res, next) => {
    console.log(req.url);
    if (!req.cookies.user && !NONEEDLOGIN.includes(req.url)) {
        next("NO LOGIN")
    }
    next()
})

app.use('/admin', async (req, res, next) => {
    const { userId } = req.cookies;
    const user = await findUserById(Number(userId))
    if (user.auth === 1) {
        next()
    }
    next("权限不足")
})


app.use("/api/user", userRouter)
app.use("/api/links", linksRouter)
app.use("/api/comments", commentRouter)
app.use("/api/discuss", discussRouter)
app.use("/api/admin", adminRouter)

//集中错误处理
app.use((err, req, res, next) => {
    console.log(err);

    if (err === "NO LOGIN") {
        res.status(200).send(err)
        return;
    }
    if (err === '权限不足') {
        req.send(err)
    }
    res.status(500).send('服务器发生未知错误');
})

app.listen(config.port, () => {
    console.log(`server start on http://localhost:${config.port}`);
})